<template>
  <div class="wrapper" px-20rpx>
    <nut-dialog v-model:visible="show" title="提示" content="是否删除" @ok="discard" />
    <city ref="cityPicker" head-title="区域选择" picker-size="4" @funcValue="confirmCity" />
    <nut-form ref="ruleForm" :model-value="form" :rules="rules">
      <nut-form-item label="收货人" prop="name">
        <nut-input v-model="form.name" class="nut-input-text" placeholder="请输入姓名" type="text" />
      </nut-form-item>
      <nut-form-item label="手机号码" prop="mobile">
        <nut-input
          max-length="11"
          v-model="form.mobile"
          class="nut-input-text"
          placeholder="请输入手机号码"
          type="text" />
      </nut-form-item>
      <nut-form-item label="所在区域" prop="consigneeAddressPath">
        <nut-input
          v-model="form.consigneeAddressPath"
          readonly
          class="nut-input-text"
          placeholder="请选择所在区域"
          type="text"
          @click="picker" />
      </nut-form-item>
      <nut-form-item label="详细地址" prop="detail">
        <nut-input v-model="form.detail" class="nut-input-text" placeholder="请输入地址" type="text" />
      </nut-form-item>
      <nut-form-item label="地址别名" prop="alias">
        <nut-input v-model="form.alias" class="nut-input-text" placeholder="请输入地址别名" type="text" />
      </nut-form-item>
      <nut-form-item label="设置默认地址" prop="isDefault">
        <nut-switch v-model="form.isDefault" active-color="#FCC300" />
      </nut-form-item>
    </nut-form>

    <!-- <div v-if="routerVal.id" text-center text-main-color mt-20rpx @click="show = true">删除</div> -->
  </div>
  <view position-fixed bottom-46rpx w-full z-999 px-40rpx box-border>
    <view
      w-670rpx
      h-100rpx
      rounded-50rpx
      bg="#FCC300"
      flex
      justify-center
      items-center
      font-500
      text="#000"
      text-32rpx
      @click="createAddress">
      保存
    </view>
  </view>
  <!-- <submit :loading="loading" :title="routerVal?.id ? '修改地址' : '新增地址'" @click="createAddress" /> -->
</template>

<script setup lang="ts">
import city from '@/components/m-city/m-city.vue'
// import submit from '@/components/sheet-btn/index.vue'
import Address from '@/components/address/instance'
import { useStore } from '@/store'
import { mobile } from '@/utils/RegExp'
import { onLoad } from '@dcloudio/uni-app'

const routerVal = ref()
const cityPicker = ref<any>(null)
const addressInstance = new Address('')
const loading = ref(false)
const store = useStore()
const form: any = ref({
  alias: '',
  consigneeAddressPath: [],
  consigneeAddressIdPath: [],
  detail: '',
  lat: '',
  lon: '',
  mobile: '',
  name: '',
  type: '',
  isDefault: false
})

const ruleForm = ref<any>(null)
const rules: any = {
  name: [
    {
      message: '请填写收货人姓名',
      required: true
    }
  ],
  mobile: [
    {
      message: '请填写正确手机号',
      required: true,
      validator: (val: string) => {
        return mobile.test(val)
      }
    }
  ],
  detail: [
    {
      message: '请填写详细地址',
      required: true
    }
  ],
  consigneeAddressPath: [
    {
      message: '请填写收货地址',
      required: true
    }
  ]
}

onLoad((val: any) => {
  routerVal.value = val
  form.value.type = val.type
  uni.setNavigationBarTitle({
    title: routerVal.value?.id ? '编辑地址' : '新增地址'
  })
  if (val.data) {
    const provideData = JSON.parse(decodeURIComponent(val.data))
    // 获取到值了给form赋值
    if (Object.keys(provideData).length) {
      Object.keys(provideData).forEach((key) => {
        form.value[key] = provideData[key]
      })
    }
  }
})
const show = ref(false)

// 删除地址
async function discard() {
  const res = await addressInstance.delete(form.value.id)
  if (res.data.success) {
    uni.showToast({
      title: '操作成功',
      icon: 'none'
    })

    setTimeout(() => {
      uni.navigateBack()
    }, 500)
  }
}

// 创建新的地址
function createAddress() {
  ruleForm.value.validate().then(async ({ valid }: any) => {
    if (valid) {
      const submit: any = { ...form.value }
      if (Array.isArray(submit.consigneeAddressIdPath))
        submit.consigneeAddressIdPath = submit.consigneeAddressIdPath.join(',')
      if (Array.isArray(submit.consigneeAddressPath))
        submit.consigneeAddressPath = submit.consigneeAddressPath.join(',')
      let res: any
      loading.value = true
      if (routerVal.value.id) res = await addressInstance.update(submit)
      else res = await addressInstance.create(submit)

      loading.value = false
      if (res.data.success) {
        uni.showToast({
          title: '操作成功',
          icon: 'none'
        })

        setTimeout(() => {
          uni.navigateBack()
        }, 500)
      }
    }
  })
}

function confirmCity(list: Array<any>) {
  const addressList: Array<string> = []
  const ids: Array<number> = []
  list.forEach((item) => {
    addressList.push(item.localName)
    ids.push(item.id)
  })
  const coord = list[list.length - 1].center.split(',')
  form.value.lat = coord[1]
  form.value.lon = coord[0]
  form.value.consigneeAddressPath = addressList
  form.value.consigneeAddressIdPath = ids
}

function picker() {
  cityPicker.value.show()
}
</script>
<style lang="scss">
page {
  $main-color: #fcc300;
}
</style>
<style scoped lang="scss"></style>
